//
//  HMComposeViewController.swift
//  WeiBoXR
//
//  Created by acer on 16/9/30.
//  Copyright © 2016年 acer. All rights reserved.
//

import UIKit
import SVProgressHUD
class HMComposeViewController: UIViewController {

    private lazy var sendButton : UIButton = {
       let button = UIButton()
        button.addTarget(self, action: #selector(btnSendAction), for: .touchUpInside)
        button.setBackgroundImage(UIImage(named: "common_button_orange"), for: .normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), for: .highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: .disabled)
        button.setTitle("发送", for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        button.setTitleColor(UIColor.white, for: .normal)
        button.setTitleColor(UIColor.gray, for: .disabled)
        button.size = CGSize(width: 45, height: 35)
        return button
    }()
    private lazy var titleLabel : UILabel = {
        let label = UILabel(textColor: UIColor.gray, fontSize: 16)
        if let name = HMUserAccountViewModel.sharedUserAccountViewModel.userAccountModel?.name {
            let result = "发微博\n" + name
            //  获取指定内容的范围
            let range = (result as NSString).range(of: name)
            let attributedStr : NSMutableAttributedString = NSMutableAttributedString(string: result)
            attributedStr.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12), NSForegroundColorAttributeName: UIColor.brown], range: range)
            label.attributedText = attributedStr
        } else {
            label.text = "发微博"
        }
        label.numberOfLines = 0
        label.textAlignment = .center
        label.sizeToFit()
        return label
    }()
    fileprivate lazy var textView : HMComposeTextView = {
        let view = HMComposeTextView()
        view.placeHolder = "哭泣,老王会笑~"
        view.font = UIFont.systemFont(ofSize: 14)
        view.delegate = self
        //  垂直方向弹簧效果开启
        view.alwaysBounceVertical = true
        return view
    }()
    fileprivate lazy var toolBar : HMStackView = {
        let view = HMStackView()
        return view
    }()
    //  发微博配图
    fileprivate lazy var pictureView: HMComposePictureView = {
        let view = HMComposePictureView()
        view.backgroundColor = self.textView.backgroundColor
        return view
    }()
    //  表情键盘
    fileprivate lazy var emoticonKeyBoard: HMEmoticonKeyboard = {
        let view = HMEmoticonKeyboard()
        //  设置大小
        view.size = CGSize(width: self.textView.width, height: 216)
        return view
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
//        setupNavUI()
        setupUI()
//        view.backgroundColor = UIColor.yellow
    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        dismiss(animated: true, completion: nil)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    private func setupNavUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        navigationItem.rightBarButtonItem?.isEnabled = false
        navigationItem.titleView = titleLabel
    }
    private func setupUI() {
        view.backgroundColor = UIColor.white
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardFrameChange(noti:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        //  监听表情按钮的点击
        NotificationCenter.default.addObserver(self, selector: #selector(didSelectedEmoticonNoti(noti:)), name: NSNotification.Name(DidSelectedEmoticonNotification), object: nil)
        //  监听删除表情按钮的点击
        NotificationCenter.default.addObserver(self, selector: #selector(didSelectedDeleteEmoticonNoti), name: NSNotification.Name(DidSelectedDeleteEmoticonNotification), object: nil)

        setupNavUI()
        view.addSubview(textView)
        view.addSubview(toolBar)
        textView.addSubview(pictureView)
        
        textView.snp_makeConstraints { (make) in
            make.top.left.right.equalTo(view)
            make.bottom.equalTo(toolBar.snp_top)
        }
        toolBar.snp_makeConstraints { (make) in
            make.left.right.equalTo(textView)
            make.bottom.equalTo(view)
            make.height.equalTo(35)
        }
        pictureView.snp_makeConstraints { (make) in
            make.centerX.equalTo(textView)
            make.top.equalTo(textView).offset(100)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(textView.snp_width).offset(-20)
        }

        toolBar.callBack = { [weak self] (type: HMComposeToolBarButtonType) in
            switch type {
            case .picture:
                print("图片")
                self?.didSelectPicture()
            case .mention:
                print("@")
            case .trend:
                print("#")
            case .emoticon:
                print("表情")
                self?.didSelectedEmoticon()
            case .add:
                print("加号")
            }
        }
        pictureView.lastCellCallBack = { [weak self] in
            self?.didSelectPicture()
        }
    }
    //  MARK: --    监听删除标签按钮的点击方法
    @objc private func didSelectedDeleteEmoticonNoti() {
        
        //  删除内容
        textView.deleteBackward()
    }

    @objc private func cancelAction() {
        self.view.endEditing(true)
        dismiss(animated: true, completion: nil)
    }
    //  MARK: --    监听表情按钮点击的方法
    @objc private func didSelectedEmoticonNoti(noti: Notification) {
        
        guard let emoticon = noti.object as? HMEmoticon else {
            return
        }
        textView.insertEmoticon(emoticon: emoticon)
        //  每次点击一个表情,保存到最近表情这组数据里面
        HMEmoticonTools.shareTools.saveRecentEmoticon(emoticon: emoticon)
        //  通知表情视图(collectionView刷新数据)
        emoticonKeyBoard.reloadRecentData()

//        if emoticon.type == "0" {
//            //  点击图片表情
////            let chs = emoticon.chs!
////            textView.insertText(chs)
//            //  记录上一次富文本
//            let lastAttbutedString = NSMutableAttributedString(attributedString: textView.attributedText)
//
//            //  图片转成富文本的流程
//            //  1. 根据表情路径创建UIImage对象
//            let image = UIImage(named: emoticon.path!)
//            //  2. 根据UIImage对象创建文本附件(NSTextAttachment)
//            let attachment = NSTextAttachment()
//            //  设置图片大小
//            //  获取字体高度
//            let lineHeight = textView.font!.lineHeight
//            //  通过设置文本附件的bounds调整图片显示位置
//            //  设置bounds会影响子控件的显示位置
//            attachment.bounds = CGRect(x: 0, y: -4, width: lineHeight, height: lineHeight)
//            attachment.image = image
//            //  3. 根据文本附件创建富文本(NSAttributedString)
//            let attributedStr = NSAttributedString(attachment: attachment)
//            //  添加这次点击的表情富文本
//            lastAttbutedString.append(attributedStr)
//            
//            //  设置富文本的字体
//            lastAttbutedString.addAttribute(NSFontAttributeName, value: textView.font!, range: NSMakeRange(0, lastAttbutedString.length))
//            
//            //  4. 设置设置富文本
//            textView.attributedText = lastAttbutedString
//
//        } else {
//            //  点击emoji标签
//            let emoji = (emoticon.code! as NSString).emoji()
//            textView.insertText(emoji!)
//        }
    }

    @objc private func keyBoardFrameChange(noti: Notification) {
        //  键盘的frame
        let keyBoardFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey]! as! NSValue).cgRectValue
        //  键盘动画时长
        let duration = (noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        //  更新约束
        toolBar.snp_updateConstraints { (make) in
            make.bottom.equalTo(view).offset(keyBoardFrame.origin.y - ScreenHeight)
        }
        //  执行约束动画
        UIView.animate(withDuration: duration) {
            self.view.layoutIfNeeded()
        }
    }
    @objc private func btnSendAction() {
        let accesstoken = HMUserAccountViewModel.sharedUserAccountViewModel.accessToken
//        let text = textView.text
        let text = textView.emoticonText //textView.text!

        if pictureView.images.count > 0 {
            let firstImage = pictureView.images.first!
            HMNetworkTools.sharedTools.upload(access_token: accesstoken!, status: text, image: firstImage, callBack: { (response, error) in
                if error != nil {
                    SVProgressHUD.showError(withStatus: "-----error-----")
                    return
                }
                SVProgressHUD.showSuccess(withStatus: "----success----")
            })
        } else {
            SVProgressHUD.show()  //为什么老师的代码加了
            HMNetworkTools.sharedTools.update(accessToken: accesstoken!, status: text) { (response, error) in
                if error != nil {
                    SVProgressHUD.showError(withStatus: "error")
                    return
                }
                SVProgressHUD.showSuccess(withStatus: "success")
            }
        }
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

//  MARK: --    处理toolbar按钮点击的逻辑
extension HMComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    //  处理点击表情逻辑
    func didSelectedEmoticon() {
        //  设置自定义视图
        if textView.inputView == nil  {
            //  从系统键盘进入到表情键盘
            textView.inputView = emoticonKeyBoard
            //  表示是表情键盘
            toolBar.showIcon(isEmoticon: true)
        } else {
            //  从表情键盘进入到系统键盘
            textView.inputView = nil
            //  表示是系统键盘
            toolBar.showIcon(isEmoticon: false)
        }
        
        //  设置键盘上面的自定义视图
        //        textView.inputAccessoryView
        //  设置第一响应者
        textView.becomeFirstResponder()
        //  重新刷新inputView
        textView.reloadInputViews()
        
        
    }

    func didSelectPicture() {
        let imagePictureCtr = UIImagePickerController()
        imagePictureCtr.delegate = self
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            imagePictureCtr.sourceType = .camera
        } else {
            imagePictureCtr.sourceType = .photoLibrary
        }
        if UIImagePickerController.isCameraDeviceAvailable(.front) {
            print("front camera OK")
        }
        if UIImagePickerController.isCameraDeviceAvailable(.rear) {
            print("rear camera OK")
        }
        imagePictureCtr.allowsEditing = true
        self.present(imagePictureCtr, animated: true, completion: nil)
        
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
//        print(Info)
        let image = info["UIImagePickerControllerOriginalImage"]! as! UIImage
//        print(image)
//        pictureView.addImage(image: image)
        let scaleImage = image.scaleImage(scaleWidth: 200)
        pictureView.addImage(image: scaleImage)
        picker.dismiss(animated: true, completion: nil)
        
    }
}

extension HMComposeViewController: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
}
